package vip.finance.makemoney.config.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import vip.finance.makemoney.common.Constant;
import vip.finance.makemoney.common.vo.UserInfo;
import vip.finance.makemoney.config.UserContext;

/**
 * @author 杨滨
 * @date 2023年02月14日
 */
@Slf4j
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    @Value("${feign.rpc.eastmoney_trade_api_url}")
    private String EASTMONEY_TRADE_API_URL;
    @Value("${feign.rpc.snow_api_url}")
    private String SNOW_API_URL;
    @Value("${feign.rpc.snow_stock_api_url}")
    private String SNOW_STOCK_API_URL;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String url = requestTemplate.feignTarget().url();
        if (url.equals(EASTMONEY_TRADE_API_URL)) {
            // 对url进行签名添加Header的操作
            UserInfo userInfo = UserContext.currentUserInfo();
            UserInfo.EastMoneyCookie eastMoneyCookie = userInfo.getCookieList().stream().filter(x -> x.getUserTradeId().equals(userInfo.getCurrentTradeUserId())).findFirst().orElse(null);
            if (eastMoneyCookie != null) {
                requestTemplate.header("cookie", eastMoneyCookie.getCookie());
                requestTemplate.query("validatekey", eastMoneyCookie.getValidatekey());
            }
        } else if (url.equals(SNOW_API_URL) || url.equals(SNOW_STOCK_API_URL)) {
            requestTemplate.header("cookie", Constant.XQ_A_TOKEN);
        }
    }
}
